package com.jbp.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.dao.BbsDao;
import com.jbp.exception.RRException;
import com.jbp.model.Bbs;
import com.jbp.model.User;
import com.jbp.model.Wallet;
import com.jbp.model.WalletRecord;
import com.jbp.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jbp.utils.PageUtils;
import com.jbp.utils.Query;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 留言板(Bbs)表服务实现类
 * @author cc
 * @since 2020-08-28 18:11:58
 */
@Service
public class BbsServiceImpl extends ServiceImpl<BbsDao, Bbs> implements BbsService {
    @Autowired
    private UserService userService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private WalletRecordService walletRecordService;

    @Autowired
    private RankProportionService rankProportionService;

    @Autowired
    private KeywordService keywordService;
    @Autowired
    private UserLevelService userLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<Bbs> queryWrapper = new QueryWrapper<>();
        if (params.get("id") != null){
            queryWrapper.like("id",params.get("id"));
        }
        IPage<Bbs> page = this.page(
                new Query<Bbs>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void add(Bbs bbs) {
        if (StringUtils.isEmpty(bbs.getContent())) {
            throw new RRException("内容不能为空");
        }
        if (bbs.getContent().length()>20) {
            throw new RRException("内容长度超过限制");
        }
        if(bbs.getTop()==0) {
            QueryWrapper<Bbs> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("top", 0);
            queryWrapper.eq("user_id", bbs.getUserId());
            queryWrapper.orderByDesc("create_time");
            queryWrapper.last("limit 1 ");
            Bbs one = getOne(queryWrapper);
            //发普通消息 30S间隔
            if (one!=null && System.currentTimeMillis()-one.getCreateTime().getTime() < 30*1000) {
                throw new RRException("发送太频繁,请稍后再试");
            } else {
                save(bbs);
            }
        } else if (bbs.getTop()==1) {
            //检查余额
            Wallet myWallet = walletService.getByUserId(bbs.getUserId());
            if (myWallet == null) {
                throw new RRException("账户异常");
            }
            int totalPrice = 1000;
            if (myWallet.getXinzuan().doubleValue()<totalPrice) {
                throw new RRException("余额不足");
            }
            //扣钱
            double afterBalance = myWallet.getXinzuan().doubleValue() - totalPrice;

            //自己添加钱包变动记录
            WalletRecord walletRecordMe = new WalletRecord();
            walletRecordMe.setOperationType("top_bbs");
            walletRecordMe.setCoinType("xinzuan");
            walletRecordMe.setAddType("sub");
            walletRecordMe.setBeforeBalance(myWallet.getXinzuan());
            walletRecordMe.setChangeBalance(BigDecimal.valueOf(totalPrice));
            walletRecordMe.setAfterBalance(BigDecimal.valueOf(afterBalance));
            walletRecordMe.setUserId(bbs.getUserId());
            walletRecordService.save(walletRecordMe);

            //百万奖池金额处理
            rankProportionService.addPrizePoolAmount(walletRecordMe.getChangeBalance());

            //自己扣钱
            myWallet.setXinzuan(BigDecimal.valueOf(afterBalance));
            walletService.updateWithLock(myWallet);

            //添加消息
            save(bbs);
        }
    }

    @Override
    public List<Bbs> latest(Map<String, Object> params) {
        int size = 200;
        if (StringUtils.isNotEmpty((String)params.get("size") )){
            size = Integer.parseInt((String) params.get("size"));
        }
        QueryWrapper<Bbs> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("top", 0);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.last("limit "+size);

        List<Bbs> list = list(queryWrapper);
        for (Bbs bbs : list) {
            User user = userService.getById(bbs.getUserId());
            if (user!=null) {
                bbs.setUserName(user.getName());
                bbs.setUserImg(user.getImg());
                bbs.setUserSex(user.getSex());
                bbs.setUserLevel(user.getLevel());
                bbs.setUserLevelOn(userLevelService.levelOn(user.getId()));
            }
            bbs.setContent(keywordService.replaceKeyWord(bbs.getContent()));
        }
        return list;
    }

    @Override
    public Bbs top() {
        QueryWrapper<Bbs> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("top", 1);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.last("limit 1 ");
        Bbs bbs = getOne(queryWrapper);
        //最多显示30分钟
        if (bbs !=null && System.currentTimeMillis()-bbs.getCreateTime().getTime() < 30*60*1000) {
            User user = userService.getById(bbs.getUserId());
            if (user!=null) {
                bbs.setUserName(user.getName());
                bbs.setUserImg(user.getImg());
                bbs.setUserSex(user.getSex());
                bbs.setUserLevel(user.getLevel());
                bbs.setUserLevelOn(userLevelService.levelOn(user.getId()));
            }
            return bbs;
        }
        return null;
    }
}
